import {
  Row,
  flexRender,
  getCoreRowModel,
  getExpandedRowModel,
  useReactTable
} from '@tanstack/react-table'
import { createColumns, getIndexs } from './columns'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@renderer/components/ui/table'
import { Button } from '@renderer/components/ui/button'
import { Card, CardContent } from '@renderer/components/ui/card'
import useInputToolSchemaStore from '@renderer/store/input-tool-schema'
import { useShallow } from 'zustand/react/shallow'
import { InputSchemaData } from '@shared/types/ai'
import React, { useMemo } from 'react'


const renderRow = (row: Row<InputSchemaData>): React.ReactNode => {
  console.log('renderRow',row)
  console.log('renderRow2',getIndexs(row))
  console.log('renderRow3',row.depth)
  return (
    <React.Fragment key={row.id}>
      {/* 当前行 */}
      <TableRow className="p-0 m-0">
        {row.getVisibleCells().map((cell) => (
          <TableCell key={cell.id} className="p-0 m-0">
            {flexRender(cell.column.columnDef.cell, cell.getContext())}
          </TableCell>
        ))}
      </TableRow>

      {/* 递归子行 */}
      {row.getIsExpanded() &&
        row.subRows.length > 0 &&
        row.subRows.map((subRow) => renderRow(subRow))}
    </React.Fragment>
  )
}

export default function InputToolSchema(): React.JSX.Element {
  const { add, data, update, remove } = useInputToolSchemaStore(
    useShallow((state) => ({
      data: state.data,
      add: state.add,
      update: state.update,
      remove: state.remove
    }))
  )

  const columns = useMemo(() => createColumns(add, update, remove), [add, update, remove])

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    enableExpanding: true,
    getSubRows: (row) => row.items,
    getExpandedRowModel: getExpandedRowModel(),
    getRowCanExpand: (row) => row.original.type === 'object' || row.original.type === 'array'
  })

  const flatRows = useMemo(() => {
    const rows: Row<InputSchemaData>[] = []
    const flatten = (rs: Row<InputSchemaData>[]) => {
      for (const r of rs) {
        rows.push(r)
        if (r.getIsExpanded() && r.subRows.length > 0) {
          flatten(r.subRows)
        }
      }
    }
    flatten(table.getRowModel().rows)
    return rows
  }, [table])

  return (
    <Card>
      <CardContent className="space-y-4">
        {/* 操作按钮区域 */}
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-semibold">输入参数配置</h3>
        </div>

        {/* 表格区域 */}
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id} className={`p-0 m-0 w-${header.getSize()}%`}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(header.column.columnDef.header, header.getContext())}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.map((row) => renderRow(row))}
            <TableRow className="p-0 m-0">
              <TableCell className="p-0 m-0">
                <Button
                  type="button"
                  variant="ghost"
                  className="text-primary hover:text-primary/80 w-full justify-center "
                  onClick={() => {
                    add([])
                  }}
                >
                  + 新增参数
                </Button>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}
